package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.common.bean.UserInfo;
import com.atguigu.gmall.common.exception.OrderException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.config.AlipayTemplate;
import com.atguigu.gmall.payment.interceptors.LoginInterceptor;
import com.atguigu.gmall.payment.pojo.PayAsyncVo;
import com.atguigu.gmall.payment.pojo.PayVo;
import com.atguigu.gmall.payment.pojo.PaymentInfoEntity;
import com.atguigu.gmall.payment.service.PaymentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

@Controller
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("pay.html")
    public String paySelect(@RequestParam("orderToken") String orderToken, Model model) {

        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();

        // 查询订单
        OrderEntity orderEntity = paymentService.queryOrderByToken(orderToken);
        if (orderEntity == null) {
            throw new OrderException("非法参数");
        }

        // 判断是否时我的订单
        if (userId != orderEntity.getUserId()) {
            throw new OrderException("当前订单不属于您");
        }

        // 判断订单状态
        if (orderEntity.getStatus() != 0) {
            throw new OrderException("当前订单不能支付");
        }

        model.addAttribute("orderEntity", orderEntity);

        return "pay";
    }

    @GetMapping("alipay.html")
    @ResponseBody
    public String toAlipay(@RequestParam("orderToken") String orderToken) {
        // 查询订单
        OrderEntity orderEntity = this.paymentService.queryOrderByToken(orderToken);
        if (orderEntity == null) {
            throw new OrderException("非法参数");
        }

        // 判断是否时我的订单
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (userId != orderEntity.getUserId()) {
            throw new OrderException("当前订单不属于您");
        }

        try {
            // 判断订单转台
            if (orderEntity.getStatus() != 0) {
                throw new OrderException("当前订单不能支付");
            }

            // 调用支付宝接口
            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(orderEntity.getOrderSn());
            payVo.setTotal_amount(orderEntity.getTotalAmount().toString());
            payVo.setSubject("谷粒商城支付平台");

            // 记录对账信息
            Long payId = paymentService.savePaymentInfo(payVo);
            payVo.setPassback_params(payId.toString());

            return alipayTemplate.pay(payVo);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("pay/success")
    public String paySuccess(@RequestParam("total_amount") String totalAmount, Model model) {
        model.addAttribute("totalAmount", totalAmount);
        return "paysuccess";
    }

    @PostMapping("pay/ok")
    @ResponseBody
    public Object payOk(PayAsyncVo payAsyncVo) {
        // 验签：确认是否时支付宝发送的
        Boolean flag = alipayTemplate.checkSignature(payAsyncVo);
        if (!flag) {
            return "failure";
        }
        // 核对订单的业务参数：app_id、out_trade_no、total_amount
        String appId = payAsyncVo.getApp_id();
        String out_trade_no = payAsyncVo.getOut_trade_no();
        String total_amount = payAsyncVo.getTotal_amount();
        // 根据passback_params获取对账记录id，查询对账记录
        String payId = payAsyncVo.getPassback_params();
        PaymentInfoEntity paymentInfoEntity = paymentService.queryPaymentInfoById(payId);
        if (!StringUtils.equals(appId, alipayTemplate.getApp_id()) ||
                !StringUtils.equals(out_trade_no,paymentInfoEntity.getOutTradeNo()) ||
                new BigDecimal(total_amount).compareTo(paymentInfoEntity.getTotalAmount()) != 0
        ) {
            return "failure";
        }

        // 校验支付状态：TRADE_SUCCESS
        String trade_status = payAsyncVo.getTrade_status();
        if (!StringUtils.equals("TRADE_SUCCESS", trade_status)) {
            return "failure";
        }

        // 修改对账记录中的支付状态
        if (paymentService.updatePaymentInfo(payAsyncVo) == 1) {
            // 发送消息给oms，标记为待发货状态
            rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "order.pay", out_trade_no);
        }

        // 响应数据给支付宝
        return "success";
    }

}
